package com.xjj.hash;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class E0811SubdomainVisitCount {

    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> countMap = new HashMap<>();
        for (String cpdomain : cpdomains) {
            String[] map = cpdomain.split(" ");
            int count = Integer.valueOf(map[0]);
            String[] words = map[1].split("\\.");
            // 从后往前加
            String str = words[words.length - 1];
            countMap.put(str, countMap.getOrDefault(str, 0) + count);
            for (int i = words.length - 2; i >= 0; i--) {
                str = words[i] + "." + str;
                countMap.put(str, countMap.getOrDefault(str, 0) + count);
            }
        }
        List<String> result = new ArrayList<>();
        for (Map.Entry<String, Integer> e : countMap.entrySet()) {
            result.add(e.getValue() + " " + e.getKey());
        }
        return result;
    }
    
}
